package com.iwdnb.gkgz.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.iwdnb.bmnf.common.excel.core.ExcelService;
import com.iwdnb.bmnf.common.model.OrderBy;
import com.iwdnb.bmnf.common.model.result.Result;
import com.iwdnb.bmnf.common.utils.BooleanUtils;
import com.iwdnb.bmnf.common.utils.ResponseUtils;
import com.iwdnb.gkgz.application.service.StockLimitUpService;
import com.iwdnb.gkgz.application.service.TulongdaoService;
import com.iwdnb.gkgz.common.model.dto.StockDayData;
import com.iwdnb.gkgz.common.model.dto.StockRangeScopeDTO;
import com.iwdnb.gkgz.common.model.dto.StockSignalDTO;
import com.iwdnb.gkgz.common.model.dto.StockSupportDTO;
import com.iwdnb.gkgz.common.quota.MovingAverage;
import com.iwdnb.gkgz.common.utils.BigDecimalUtils;
import com.iwdnb.gkgz.common.utils.RealtimeStockUtils;
import com.iwdnb.gkgz.common.utils.StockAverageUtils;
import com.iwdnb.gkgz.common.utils.StockAverageUtils.StepBackAverage;
import com.iwdnb.gkgz.common.utils.StockUtils;
import com.iwdnb.gkgz.common.utils.WorkDayUtils;
import com.iwdnb.gkgz.common.utils.WorkTimeUtils;
import com.iwdnb.gkgz.infrastructure.dao.repo.StockDayDataRepository;
import com.iwdnb.gkgz.infrastructure.dao.repo.impl.StockDayDataLocalRepositoryImpl;
import com.iwdnb.wwzy.dao.MetaDataDAO;
import com.iwdnb.wwzy.model.query.MetaQuery;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.iwdnb.gkgz.common.constant.GkgzConstants.OBJECT_CODE_STOCK_SIGNAL;

/**
 * 测试
 **/
@RestController
@RequestMapping("/api/stock/tld")
@Slf4j
public class TulongdaoController {
    @Autowired
    private TulongdaoService tulongdaoService;
    @Autowired
    private StockLimitUpService stockLimitUpService;
    @Autowired
    private ExcelService excelService;

    /**
     * 屠龙刀信号校验
     *
     * @return
     */
    @RequestMapping("/tldCheckSignal")
    public Result<String> tldCheckSignal(String beginDate, String endDate, String code, String sellFlag,
        String sendDingtalkFlag, String forceFlag) {
        Date begin = DateUtil.beginOfDay(DateUtil.parseDate(beginDate));
        Date end = DateUtil.endOfDay(DateUtil.parseDate(endDate));
        for (int i = 0; i < 10000; i++) {
            if (WorkDayUtils.isWorkDay(begin) && WorkDayUtils.isWeekNormalDay(begin)) {
                boolean isToday = DateUtil.formatDate(begin).equals(DateUtil.formatDate(new Date()));
                boolean realtimeFlag = isToday && WorkTimeUtils.isWorkingTime();
                tulongdaoService.checkSignal(begin, code, sellFlag, realtimeFlag, BooleanUtils.isTrue(sendDingtalkFlag),
                    BooleanUtils.isTrue(forceFlag));
            }
            begin = DateUtil.offsetDay(begin, 1);
            if (begin.after(end)) {
                break;
            }

        }
        return Result.getSuccessResult(null);
    }

    /**
     * 屠龙刀卖出信号校验
     *
     * @return
     */
    @RequestMapping("/tldSell")
    public Result<String> tldSell(String beginDate, String endDate, String sendDingtalkFlag) {
        Date begin = DateUtil.parseDate(beginDate);
        Date end = DateUtil.endOfDay(DateUtil.parseDate(endDate));

        for (int i = 0; i < 10000; i++) {
            if (WorkDayUtils.isWorkDay(begin) && WorkDayUtils.isWeekNormalDay(begin)) {
                tulongdaoService.tldSell(begin, BooleanUtils.isTrue(sendDingtalkFlag));
            }
            begin = DateUtil.offsetDay(begin, 1);
            if (begin.after(end)) {
                break;
            }

        }
        return Result.getSuccessResult(null);
    }

    /**
     * 设置涨停板屠龙刀标识
     *
     * @return
     */
    @RequestMapping("/setLimitUpDataTldFlag")
    public Result<String> setLimitUpDataTldFlag(String date) {
        Date begin = DateUtil.parseDate(date);
        stockLimitUpService.setTldFlag(begin);
        return Result.getSuccessResult(null);
    }

    /**
     * 屠龙刀手动卖出
     *
     * @return
     */
    @RequestMapping("/tldManualSell")
    public Result<String> tldManualSell(String codes) {
        tulongdaoService.tldManualSell(codes, new Date());
        return Result.getSuccessResult(null);
    }

    /**
     * 设置屠龙刀市场行情为差,good/bad
     *
     * @return
     */
    @RequestMapping("/tldSetMarketType")
    public Result<String> tldSetMarketType(String type) {
        tulongdaoService.tldSetMarketType(type);
        return Result.getSuccessResult(null);
    }

    /**
     * 预测屠龙刀明日股价支撑位
     *
     * @return
     */
    @RequestMapping("/predictTldSupportPrice")
    public Result<String> predictTldSupportPrice(String date, String codes) {
        List<StockSupportDTO> supportDataList = tulongdaoService.predictTldSupportPrice(date, codes);
        return Result.getSuccessResult(null);
    }

    /**
     * 屠龙刀导出明日股价支撑位
     *
     * @return
     */
    @RequestMapping("/downloadTldSupportData")
    public Result<String> downloadTldSupportData(String date, String codes, String checkFlag, String filterMatchFlag)
        throws IOException {
        List<StockSupportDTO> supportDataList = tulongdaoService.predictTldSupportPrice(date, codes);
        if (CollectionUtils.isEmpty(supportDataList)) {
            return Result.getErrorResult("无数据");
        }
        for (StockSupportDTO supportDTO : supportDataList) {
            supportDTO.setName(StockUtils.getStock(supportDTO.getCode()).getName());
            supportDTO.setRealtimePrice(RealtimeStockUtils.getRealtimeData(supportDTO.getCode()).getClosePrice());
            if (Objects.nonNull(supportDTO.getFirst())) {
                supportDTO.setSupportRate(BigDecimalUtils.subStractAndDividePrecent(supportDTO.getRealtimePrice(),
                    supportDTO.getFirst().getPrice()));
            }
        }
        boolean isToday = StringUtils.equals(date, DateUtil.formatDate(new Date()));
        if (BooleanUtils.isTrue(checkFlag) && !isToday) {
            supportDataList = tulongdaoService.checkPreditction(supportDataList, date);
            if (BooleanUtils.isTrue(filterMatchFlag)) {
                supportDataList = supportDataList.stream().filter(item -> BooleanUtils.isTrue(item.getMatchFlag()))
                    .collect(Collectors.toList());
            }
        }
        Collections.sort(supportDataList, Comparator.comparing(StockSupportDTO::getScore).reversed());
        Date d = WorkDayUtils.getNextWorkDay(DateUtil.parseDate(date));
        if (CollectionUtils.isNotEmpty(supportDataList)) {
            File file = new File(
                "/Users/wubinchuan/Documents/temp/tldSupport/tldSupport_" + DateUtil.formatDate(d) + ".xlsx");
            excelService.exportExcel(supportDataList, new FileOutputStream(file));
        }
        return Result.getSuccessResult(null);
    }

    /**
     * 统计股票特征信息
     * type:1=涨停次日无上影线的阴柱
     *
     * @return
     */
    @RequestMapping("/staticTldInfo")
    public Result<JSONObject> staticTldInfo(String begin, String end, String codes, String type) {
        JSONObject jsonObject = tulongdaoService.staticTldInfo(begin, end, codes, type);
        return Result.getSuccessResult(jsonObject);
    }
}
